package com.itheima.dubbo.api.mongo.impl;

import cn.hutool.core.collection.CollUtil;
import com.itheima.dubbo.api.mongo.UserLocationApi;
import com.tanhua.model.mongo.UserLocation;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class UserLocationApiImpl implements UserLocationApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 更新或者插入当前用户的地理位置
     * @param userId
     * @param longitude
     * @param latitude
     * @param addrStr
     */
    @Override
    public void updateOrSaveLocation(Long userId, Double longitude, Double latitude, String addrStr) {
        //1. 先获取当前用户的地理位置
        Query query = new Query(Criteria.where("userId").is(userId));
        //2. 判断是否存在地理位置，
        if(!mongoTemplate.exists(query, UserLocation.class)){
            //3. 如果不存在插入
            UserLocation userLocation = new UserLocation();
            userLocation.setUserId(userId);
            userLocation.setLocation(new GeoJsonPoint(longitude,latitude));
            userLocation.setAddress(addrStr);
            userLocation.setCreated(System.currentTimeMillis());
            userLocation.setUpdated(System.currentTimeMillis());
            userLocation.setLastUpdated(System.currentTimeMillis()); //上次的更新时间
            mongoTemplate.save(userLocation);
        }else {
            UserLocation userLocation = mongoTemplate.findOne(query, UserLocation.class);
            //4 如果存在更新
            Update update = new Update();
            update.set("location",new GeoJsonPoint(longitude,latitude));
            update.set("address",addrStr);
            update.set("updated",System.currentTimeMillis());
            update.set("lastUpdated",userLocation.getUpdated());

            mongoTemplate.updateFirst(query,update,UserLocation.class);

        }


    }

    @Override
    public List<Long> queryNearUser(Long userId, Integer distance) {
        //1. 根据用户id查找所在位置， 这个位置其实就是圆心（以你为中心）
        Query query = new Query(Criteria.where("userId").is(userId));
        UserLocation userLocation = mongoTemplate.findOne(query, UserLocation.class);
        GeoJsonPoint location = userLocation.getLocation();
        //2. 画半径
        Distance distance1=null;
        if(distance!=0) {
            distance1 = new Distance(distance / 1000, Metrics.KILOMETERS); //传递的过来单位是米
        }

        //3. 创建圆
        Circle circle = new Circle(location,distance1);

        Query searchQuery = new Query(Criteria.where("location").withinSphere(circle));
        //4. 搜索
        List<UserLocation> userLocationList = mongoTemplate.find(searchQuery, UserLocation.class);


        return CollUtil.getFieldValues(userLocationList,"userId",Long.class);
    }
}
